package com.appistry.api.rest.domain;

import java.util.HashMap;
import java.util.Iterator;

public class RestResource {
	private static final String DELIMITER = "/";
	private static final String AMPERSAND = "&";
	private static final String QUESTION_MARK = "?";
	private static final String EQUAL = "=";	
	private final String resource;	
	private final HashMap<String,Object> varMap = new HashMap<String, Object>();	
	
	public RestResource(String resource){
		this.resource = resource;
	}
	
	public RestResource(String... resourceParts){
		//Do the math to do initial size		
		int n = resourceParts.length;
		int initSize = 1;
		if(n > 1){
			initSize = 2 * n - 1;
		}		
		
		StringBuilder sb = new StringBuilder(initSize);
		
		for(int i=0; i<resourceParts.length; i++){
			sb.append(resourceParts[i]);
			
			// Are there more parts?
			if(i < resourceParts.length - 1){
				sb.append(DELIMITER);
			}
		}
		
		this.resource = sb.toString();
	}
	
	public String getResourceUrl(){
		//Do the math to do initial size		
		int n = 1 + varMap.size();
		int initSize = 1;
		if(n == 2){
			initSize = 5;
		}else if(n > 2){
			initSize = 3*n + n - 3;
		}		
		
		StringBuilder sb = new StringBuilder(initSize);
		sb.append(resource);
		
		if(varMap.size() > 0){			
			sb.append(QUESTION_MARK);
			
			//Add the vars
			Iterator<String> itr = varMap.keySet().iterator();
			while(itr.hasNext()){
				String key = itr.next();
				Object value = varMap.get(key);
				
				//key=value
				sb.append(key);
				sb.append(EQUAL);
				sb.append(value);
				
				if(itr.hasNext()){
					sb.append(AMPERSAND);
				}
			}
		}
		
		return sb.toString();
	}
	
	public void putKeyValuePair(String key, Object value){
		varMap.put(key, value);
	}
	
	public Object removeKey(String key){
		return varMap.remove(key);
	}
	
	public void clearKeyValuePairs(){
		varMap.clear();
	}
}
